<!-- 购物车初版 -->
<template>
	<view>
		<checkbox-group @change="changeCheckbox">
			<view class="item" v-for="(item,index) in cart" :key="item.id">
				<checkbox :value="item.id" :checked="item.checked"></checkbox>
				<text class="title">{{item.name}}</text>
				<text class="price">￥{{item.price}}</text>
				<text class="del" @click="delItem(index)">删除</text>
			</view>
			<view class="sum">总计{{checkGroup.length}}个，总价格{{total}}元</view>
		</checkbox-group>
	</view>
</template>

<script setup>
	import {
		ref,computed
	} from 'vue'
	const cart = ref([{
			id: '1',
			name: '小米',
			price: 123,
			checked:false
		},
		{
			id: '2',
			name: '华为',
			price: 234,
			checked:false
		},
		{
			id: '3',
			name: 'oppo',
			price: 345,
			checked:false
		},
		{
			id: '4',
			name: 'vivo',
			price: 456,
			checked:false
		}
	])
	const checkGroup = ref([])
	//删除事件
	const delItem = (index) => {
		cart.value.splice(index, 1)
	}
	//check选中事件
	const changeCheckbox = (e)=>{
		checkGroup.value = e.detail.value
		cart.value.forEach((item)=>{
			item.checked = checkGroup.value.includes(item.id)
		})
	}
	const total = computed(()=>{
	return	cart.value.filter(item=>item.checked).reduce((prev,curr)=>prev+curr.price,0)
	})
</script>

<style lang="scss">
	.item {
		padding: 20rpx;
		.title {
			margin: 0 10rpx;
			font-size: 30rpx;
		}
		.price{
			margin:  0 10rpx;
		}
		.del {
			font-size: 30rpx;
			color: red;
			margin-left: 20rpx;
		}
	}
	.sum{
		margin-top: 30rpx;
		padding-left: 30rpx;
	}
</style>